﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DevToolBox.Cloud.Common;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;

namespace DevToolBox.Cloud.Azure
{
    /// <summary>
    /// Class to encapsuate operations in Micorosft Azure Table storage
    /// </summary>
    public class TableStorageOperations : IManageable
    {

        private CloudTableClient tableClient = null;

        /// <summary>
        /// Default constructor
        /// </summary>
        public TableStorageOperations()
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
            CloudConfigurationManager.GetSetting("AzureStorageConnectionString"));
            tableClient = storageAccount.CreateCloudTableClient();
        }

        /// <summary>
        /// Method to create a new table
        /// </summary>
        /// <param name="configObject">List of TableInfo objects</param>
        public void Create(object configObject)
        {
            if (configObject == null)
            {
                return;
            }

            TableInfo tableMetaData = (TableInfo)configObject;
            CloudTable table = tableClient.GetTableReference(tableMetaData.Name);
            table.CreateIfNotExists();
        }

        /// <summary>
        /// Method to delete a table if exists
        /// </summary>
        /// <param name="key">Table Name</param>
        public void Delete(string key)
        {
            if (tableClient != null)
            {
                CloudTable table = tableClient.GetTableReference(key);
                table.DeleteIfExists();
            }
        }

        /// <summary>
        /// Method to know if a table exists or not
        /// </summary>
        /// <param name="key">Table Name</param>
        /// <returns>The "ACTIVE" string</returns>
        /// <remarks>
        /// The Table Storage API only returns a boolean 
        /// to represent if the Table exists or not
        /// </remarks>
        public string GetStatus(string key)
        {
            if (tableClient != null)
            {
                CloudTable table = tableClient.GetTableReference(key);
                if (table.Exists())
                {
                    return "ACTIVE";
                }
            }

            return null;
        }

        /// <summary>
        /// Method to Dispose unmanaged resources
        /// </summary>
        public void Dispose()
        {
            throw new NotImplementedException();
        }

        public void Update(object configObject)
        {
            //This operation is not needed yet
            throw new NotImplementedException();
        }
    }
}
